package main

import (
	"edgex_back_management/defs"
	"edgex_back_management/handlers"
	"edgex_back_management/session"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

type middleWareHandler struct {
	r *httprouter.Router
}

func NewMiddleWareHandler(r *httprouter.Router) http.Handler {
	m := middleWareHandler{}
	m.r = r
	return m
}

func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// check session
	ok := handlers.ValidateUserSession(r)
	if ok {
		m.r.ServeHTTP(w, r)
	} else {
		defs.SendErrorResponse(w, defs.ErrorAuthExpired)
	}

}

func RegisterHandlers() *httprouter.Router {
	router := httprouter.New()

	router.GET("/", handlers.IndexHandler)

	router.POST("/user/login", handlers.Login)
	router.GET("/user/home", handlers.HomeHandler)
	router.GET("/user/logout/:userName", handlers.Logout)
	router.GET("/user/getByName/:userName", handlers.FindUserInfo)

	router.GET("/article/getArticle/:id", handlers.GetArticle)
	router.GET("/articles/:from/:size", handlers.FindAllArticle)
	router.GET("/article/passArticle/:id", handlers.PassArticle)
	router.GET("/article/rejectArticle/:id", handlers.RejectArticle)
	router.GET("/article/deleteArticle/:id", handlers.DeleteArticle)

	router.ServeFiles("/statics/*filepath", http.Dir("./templates"))
	return router
}

func loadSessionCache() {

	ok := session.LoadAndCacheSessions()
	if ok {
		log.Printf("User Sessions Load successed!")
	}
}

func main() {
	loadSessionCache()

	r := RegisterHandlers()
	handler := NewMiddleWareHandler(r)

	//ok := dbops.DBConnect()
	//ok := true
	//if ok {
	//	log.Println("connect to db success!")
	//} else {
	//	log.Println("failed connect to db!")
	//}

	log.Println("Server Listening :Port(8080)")
	http.ListenAndServe(":8080", handler)

}
